package servlet;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import serviceImple.UserServiceImpl;

@WebServlet("/loginservlet")
public class LoginServlet extends HttpServlet {
	UserServiceImpl userServiceImpl = new UserServiceImpl();
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("userName");
		String password = request.getParameter("password");
		String iscookie = null == request.getParameter("iscookie") ? "no" : request.getParameter("iscookie");
		if (userServiceImpl.login(name, password)) {
			
			if (Objects.equals(iscookie, "yes")) {
				Cookie cookie = new Cookie("web", "www.nnblog.com");
				cookie.setMaxAge(60 * 60 * 24);
				response.addCookie(cookie);
			}
			HttpSession session = request.getSession();
			session.setAttribute("name", name);
			request.getRequestDispatcher("view/main.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
